// app.js
import {promisifyAll} from 'miniprogram-api-promise'
const wxp=wx.p={}
promisifyAll(wx,wxp)
App({
  globalData:{
    islogined:false,
    autologin:false,
    openid:"",
    url:'https://bookstore.hikki.site',
    userInfo:"",
  },
  onLaunch: async function () {
    wx.showLoading({
      title: '拼命加载中...',
    });
    await this.checkLoginStatus();
       // 模拟异步操作，实际情况根据具体需求而定
    wx.hideLoading();   
  },

  checkLoginStatus: async function () {
      const loginRes = await wx.login();
      const requestRes = await wx.p.request({
        method: "GET",
        url: this.globalData.url + '/login/getOpenid?code=' + loginRes.code,
      }); // 发送请求并等待返回结果
      console.log(requestRes.data.data)
      this.globalData.openid = requestRes.data.data.openId;
      if (requestRes.data.data.islogin) {
        this.globalData.islogined = true;
        // 如果已登录，则获取用户信息并设置页面数据
        if (requestRes.data.data.autologin) {
          this.globalData.autologin = true;
          this.islogin();
        }
        
      }
  },
  
  async islogin(){
      const userInfo=await wx.p.request({
        url: this.globalData.url+'/login/getUser',
        method:"GET",
        data:{
          openid:this.globalData.openid
        },
      })
      console.log(userInfo.data.data[0])
      if (userInfo.data.data[0]) { // 添加检查以确保 userInfo 是有效的
        this.globalData.userInfo=userInfo.data.data[0]
      } else {
        console.error('Failed to get user info');
      }
      
  },
  //查看授权信息
  getsetting(){
    var that=this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] !== true) {
          // 用户未授权，需要弹出授权窗口
          that.getauthorize()
        } else if (res.authSetting['scope.userLocation'] === undefined) {
          // 用户未决定，需要弹出授权窗口
          that.getauthorize()
        }
      }
    })
  },
  //获取权限
  getauthorize(){
    var that=this
    wx.authorize({
      scope: 'scope.userLocation'
    })
  },

}); 
